<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active{
      background-color: red;
    }
  </style>
</head>
<body>
  <div id="app">
    <router-link tag="button" to="/home">首页</router-link>
    <router-link tag="button" to="/news">新闻页</router-link>
    <router-link tag="button" replace to="/about">关于我们</router-link>
    <hr>
    <router-view></router-view>
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    // 定义好路由组件的options
    const Home = {
      template: `
        <div>
          <h2>我是home页</h2>
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h2>我是news页</h2>
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h2>我是about页</h2>
        </div>
      `
    }
    const NotFound = {
      template: `
        <div>
          <h2>我是404页</h2>
        </div>
      `
    }
    const routes = [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home
      },
      {
        path: '/news',
        component: News
      },
      {
        path: '/about',
        component: About
      },
      {
        path: '*',
        component: NotFound
      }
    ]
    const router = new VueRouter({
      routes
    })
    // 添加路由全局前置守卫
    /* 
      全局前置守卫发生在路由变化，路由组件匹配之前
        回调函数的三个参数
          to
            跳转过来的路由传参信息  （也可以在目标路由组件中通过this.$route拿到）
          from
            从哪跳过来的路由参数信息
          next 
            放行的函数，每一 回调触发，代码执行必须 有且只能头一个 next触发
              注意：需要你写条件分支时，注意你的分支结构
              next触发可以出传参
                参数同 router-link的to属性或者push和replace的参数
                控制最终跳转的路由地址
                next('/home')
                next({
                  path: '/news',
                  query: {
                    a: 10
                  }
                })
    */
    router.beforeEach((to, from, next) => {
      if(to.path === "/about"){
        next('/news');
      }else{
        next();
      }
    
    })
    const vm = new Vue({
      el: '#app',
      router
    })
  </script>
</body>
</html>